package com.filldream.fastboot.core.mq;

import lombok.extern.slf4j.Slf4j;
import org.apache.activemq.ScheduledMessage;
import org.apache.activemq.command.ActiveMQQueue;
import org.apache.activemq.command.ActiveMQTopic;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.jms.*;
import java.util.Date;

@Slf4j
@Service
public class MqProducer {

    @Resource
    private JmsMessagingTemplate jmsMessagingTemplate;

    /**
     * 普通queue队列
     * @param destinationName
     * @param message
     */
    public void sendMsg(String destinationName,String message){
        Destination destination=new ActiveMQQueue(destinationName);
        jmsMessagingTemplate.convertAndSend(destination,message);
    }

    /**
     * 延迟发送
     * @param queueName 消息queue
     * @param text  消息内容
     * @param startTime 消息需要消费的时间
     */
    public void delaySend( String queueName, String text, Date startTime) {
        Long size = startTime.getTime() - new Date().getTime();
        if(size >= 0){
            delaySend(queueName,text, size);
        }
    }

    /**
     * 延迟发送
     * @param queueName
     * @param text
     * @param time
     */
    public void delaySend( String queueName, String text, Long time) {
        //获取连接工厂
        ConnectionFactory connectionFactory = this.jmsMessagingTemplate.getConnectionFactory();
        try {
            //获取连接
            Connection connection = connectionFactory.createConnection();
            connection.start();
            //获取session
            Session session = connection.createSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);
            // 创建一个消息队列
            Destination destination = session.createQueue(queueName);
            MessageProducer producer = session.createProducer(destination);
            producer.setDeliveryMode(DeliveryMode.PERSISTENT);
            TextMessage message = session.createTextMessage(text);
            //设置延迟时间
            message.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, time);
            //发送
            producer.send(message);
            session.commit();
            producer.close();
            session.close();
            connection.close();
        } catch (Exception e) {
            e.getMessage();
        }
    }

    /**
     * 发送主题消息
     * @param topic
     * @param message
     */
    public void sendMsgTopic(String topic,String message){
        Topic destination = new ActiveMQTopic(topic);
        jmsMessagingTemplate.convertAndSend(destination,message);
    }
}